package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.RelativeLayout;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.storage.GroupSqlManager;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.ui.group.GroupMemberService;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.listeners.CheckBoxCheckListener;
import com.yuntongxun.ecdemo.voicechat.listeners.LoadMoreClickListener;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadView;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadViewImpl;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.ui.adapter.ChoosePartnersAdapter;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.NetUtils;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.ExStaggeredGridLayoutManager;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderSpanSizeLookup;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.OnRecyclerViewScrollListener;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.RecyclerViewUtils;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECGroupManager;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.im.ECGroup;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * 勾选好友进群
 * Created by Administrator on 2016/11/28.
 */

public class ChoosePartnersActivity extends BaseVoiceChatActivity implements ICommonViewUi, CheckBoxCheckListener, LoadMoreClickListener,
        SwipeRefreshLayout.OnRefreshListener,ECGroupManager.OnCreateGroupListener , GroupMemberService.OnSynsGroupMemberListener {

    public static final String ACCOUNT="account";
    public static final String GROUP_NAME="group_name";
    public static final String GROUP_INTROUDCTION="group_introduction";

    private String groupName="";
    private String groupIntroudction="";
    @InjectView(R.id.swipe_refresh_layout)
    public SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.recycler_view)
    public RecyclerView recyclerView;

    @InjectView(R.id.search_layout)
    RelativeLayout searchLayout;

    private HeaderAndFooterRecyclerViewAdapter adapter;
    private ExStaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<UserInfo> mResultList = new ArrayList<UserInfo>();

    private ICommonRequestPresenter iCommonRequestPresenter = null;

    private ILoadView iLoadView = null;

    private View loadMoreView = null;

    private boolean isRequesting = false;//标记，是否正在刷新

    private int mCurrentPage = 0;

    String accountName="";


    private boolean mNeedResult;

    public static final String FROME_INVITE="from_invite";
    private boolean isFromInvite=false;
    public static final String GROUP_ID="group_id";
    private String groupId="";

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_member;
    }

    @Override
    protected void initViewsAndEvents() {
        setTitle("Choose");
        setRightTitle("Confirm");

        mNeedResult = getIntent().getBooleanExtra("group_select_need_result", false);
        accountName=getIntent().getStringExtra(ACCOUNT);
        if (!mNeedResult){
            groupName=getIntent().getStringExtra(GROUP_NAME);
            groupIntroudction=getIntent().getStringExtra(GROUP_INTROUDCTION);
        }

        if (getIntent().hasExtra(FROME_INVITE)){
            isFromInvite=true;
            groupId=getIntent().getStringExtra(GROUP_ID);
        }

        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);

        iLoadView = new ILoadViewImpl(mContext, this);

        loadMoreView = iLoadView.inflate();
        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new MyScrollListener());

        searchLayout.setVisibility(View.GONE);

        refreshListView();

        //第一次进来时刷新
        if (NetUtils.isNetworkConnected(mContext)) {
            if (null != swipeRefreshLayout) {

                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        swipeRefreshLayout.setRefreshing(true);

                        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
                    }
                }, ApiConstants.Integers.PAGE_LAZY_LOAD_DELAY_TIME_MS);
            }
        }
    }

    public void refreshListView() {

        ChoosePartnersAdapter mIntermediary = new ChoosePartnersAdapter(mContext, mResultList, this);

        adapter = new HeaderAndFooterRecyclerViewAdapter(mIntermediary);

        recyclerView.setAdapter(adapter);

        if (mResultList.size() >= ApiConstants.Request.PAGE_NUMBER) {

            RecyclerViewUtils.setFooterView(recyclerView, loadMoreView);
        }
        staggeredGridLayoutManager = new ExStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        staggeredGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), staggeredGridLayoutManager.getSpanCount()));

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
    }

    @Override
    public void onRefresh() {
        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
    }


    @Override
    public void toRequest(int eventTag) {
        if(eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT){
            //刷新

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                swipeRefreshLayout.setRefreshing(false);
                return;
            }

            mCurrentPage = 1;

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "30");

            iCommonRequestPresenter.request(ApiConstants.EventTags.REFRESH_LIST_EVENT, mContext, ApiConstants.Urls.FRIEND_LIST, map);

        }else if(eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT){
            //加载更多

            if (isRequesting)
                return;

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                iLoadView.showErrorView(loadMoreView);
                return;
            }

            if (mResultList.size() < ApiConstants.Request.PAGE_NUMBER) {
                return;
            }

            mCurrentPage++;

            iLoadView.showLoadingView(loadMoreView);

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "30");
            iCommonRequestPresenter.request(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT, mContext, ApiConstants.Urls.FRIEND_LIST, map);
        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {
        if(eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT){
            //下拉刷新

            List<UserInfo> resultList = parseResult(result);

            mResultList.clear();
            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
//            mResultList.addAll(resultList);
            List<ECContacts> contacts=new ArrayList<>();
            for (int i=0;i<resultList.size();i++){
                ECContacts contact=new ECContacts();
                UserInfo info=mResultList.get(i);
                StringBuffer message= new StringBuffer();
                message.append("{\"result\":" );
                message.append("{\"accountName\":\"" + info.getAccountName() + "\",");
                message.append("\"nickName\":\"" + info.getNickName() + "\",");
                message.append("\"id\":\"" + info.getId() + "\",");
                message.append("\"gender\":\"" + info.getGender() + "\",");
                message.append("\"age\":\"" + info.getAge() + "\",");
                message.append("\"country\":\"" + info.getCountry() + "\",");
                message.append("\"nativeLanguage\":\"" + info.getNativeLanguage() + "\",");
                message.append("\"learningLanguage\":\"" + info.getLearningLanguage() + "\"}}");
                contact.setNickname(info.getNickName()+"("+message.toString()+")");
                contact.setContactid(info.getId());
                contacts.add(contact);
            }
            ContactSqlManager.insertContacts(contacts);
            refreshListView();


        }else if(eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT){
            //加载更多

            List<UserInfo> resultList = parseResult(result);

            mResultList.addAll(resultList);
            List<ECContacts> contacts=new ArrayList<>();
            for (int i=0;i<resultList.size();i++){
                ECContacts contact=new ECContacts();
                UserInfo info=mResultList.get(i);
                StringBuffer message= new StringBuffer();
                message.append("{\"result\":" );
                message.append("{\"accountName\":\"" + info.getAccountName() + "\",");
                message.append("\"nickName\":\"" + info.getNickName() + "\",");
                message.append("\"id\":\"" + info.getId() + "\",");
                message.append("\"gender\":\"" + info.getGender() + "\",");
                message.append("\"age\":\"" + info.getAge() + "\",");
                message.append("\"country\":\"" + info.getCountry() + "\",");
                message.append("\"nativeLanguage\":\"" + info.getNativeLanguage() + "\",");
                message.append("\"learningLanguage\":\"" + info.getLearningLanguage() + "\"}}");
                contact.setNickname(mResultList.get(i).getNickName()+"("+message.toString()+")");
                contact.setContactid(mResultList.get(i).getId());
                contacts.add(contact);
            }
            ContactSqlManager.insertContacts(contacts);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 解析结果
     *
     * @param result
     * @return
     */
    public List<UserInfo> parseResult(String result) {
        JsonHelper<UserInfo> dataParser = new JsonHelper<UserInfo>(
                UserInfo.class);
        return dataParser.getDatas(
                result, "list");
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        isRequesting = status;

        if (!status) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


//    @Override
//    public void onItemClick(int position) {
//        UserInfo info=mResultList.get(position);
//        ECContacts mContacts = ContactSqlManager.getCacheContact(info.getAccountName());
//        if(mContacts == null) {
//            mContacts = new ECContacts(info.getAccountName());
//            mContacts.setNickname(info.getNickName());
//        }
//
//        if(mContacts == null) {
//            ToastUtil.showMessage(R.string.contact_none);
//            return ;
//        }
//        CCPAppManager.startChattingAction(this, mContacts.getContactid(), mContacts.getNickname(), true);
//    }

    @Override
    public void clickLoadMoreData() {
        toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
    }


    List<UserInfo> userInfoList=new ArrayList<>();
    @Override
    public void onCheckBoxCheck(int position,boolean ischeck) {
        if (ischeck){
            userInfoList.add(mResultList.get(position));
        }else{
            for (int i=0;i<userInfoList.size();i++){
                if (mResultList.get(position).getAccountName().equals(userInfoList.get(i).getAccountName())){
                    userInfoList.remove(i);
                    break;
                }
            }
        }

    }

    @OnClick(R.id.toolbar_right_title)
    public void onRightTitleClick(){

        if (userInfoList==null||userInfoList.size()==0){
            showToastLong("Please select your partners");
            return;
        }

        String chatuser =getChatuser();

        String[] split = chatuser.split(",");
        phoneArr=split;
//        String userNameArr=getChatuserName();
//        String[] memberArrs= userNameArr.split(",");

        if (split.length > 0&& !mNeedResult) {
            showCommonProcessDialog(null);
            SDKCoreHelper.getECGroupManager().createGroup(getDisGroup(), this);
            return;
        }

        if(mNeedResult) {
            if (isFromInvite){
                GroupMemberService.inviteMembers(groupId, "",
                        ECGroupManager.InvitationMode.FORCE_PULL, phoneArr);
            }
//            Intent intent = new Intent();
//            intent.putExtra("Select_Conv_User", split);
//            setResult(-1, intent);
//            finish();
//            return ;
        }
    }

    /**
     *
     * 获取讨论组名称
     */
    private ECGroup getDisGroup() {
        ECGroup group = new ECGroup();
        // 设置讨论组名称
        group.setName(groupName);
        // 设置讨论组公告
        group.setDeclare(groupIntroudction);
        group.setScope(ECGroup.Scope.TEMP);
        // 讨论组验证权限，需要身份验证
        group.setPermission(ECGroup.Permission.AUTO_JOIN);
        // 设置讨论组创建者
        group.setOwner(CCPAppManager.getUserId());

        group.setProvince("");
        group.setCity("");
        group.setIsDiscuss(true);
        return group;
    }

    /**
     * 选择的联系人
     */
    public String getChatuser() {
        StringBuilder selectUser = new StringBuilder();
        List<ECContacts> contacts=new ArrayList<>();
        for(int i=0;i<userInfoList.size();i++) {
            ECContacts contact=new ECContacts();
            UserInfo info=userInfoList.get(i);
            StringBuffer message= new StringBuffer();
            message.append("{\"result\":" );
            message.append("{\"accountName\":\"" + info.getAccountName() + "\",");
            message.append("\"nickName\":\"" + info.getNickName() + "\",");
            message.append("\"id\":\"" + info.getId() + "\",");
            message.append("\"gender\":\"" + info.getGender() + "\",");
            message.append("\"age\":\"" + info.getAge() + "\",");
            message.append("\"country\":\"" + info.getCountry() + "\",");
            message.append("\"nativeLanguage\":\"" + info.getNativeLanguage() + "\",");
            message.append("\"learningLanguage\":\"" + info.getLearningLanguage() + "\"}}");
            contact.setNickname(info.getNickName()+"("+message.toString()+")");
            contact.setContactid(info.getId());
            contacts.add(contact);
            if(contact != null ) {
                LogUtil.e("contact",info.getId());
                selectUser.append(info.getId()).append(",");
            }
        }
        ContactSqlManager.insertContacts(contacts);
        if(selectUser.length() > 0) {
            selectUser.substring(0, selectUser.length() - 1);
        }
        return selectUser.toString();
    }

    private String[] phoneArr;
    ECGroup mGroup;
    @Override
    public void onCreateGroupComplete(ECError error, ECGroup group) {
        dismissCommonPostingDialog();
        if (error.errorCode == SdkErrorCode.REQUEST_SUCCESS) {
            mGroup=group;
            // 创建的群组实例化到数据库
            // 其他的页面跳转逻辑
            mGroup.setIsNotice(true);
            GroupSqlManager.insertGroup(mGroup, true, false, true);

            showCommonProcessDialog("");
            GroupMemberService.inviteMembers(mGroup.getGroupId(), "",
                    ECGroupManager.InvitationMode.FORCE_PULL, phoneArr);

            PostResult postResult = new PostResult();
            postResult.setTag(EventBusTags.CREATE_GROUP_SUCCESS);
            EventBus.getDefault().post(postResult);
            finish();

        } else {
//            ToastUtil.showMessage("创建讨论组失败[" + error.errorCode + "]");
            ToastUtil.showMessage("Create failed");

            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        GroupMemberService.addListener(this);
    }

    @Override
    public void onSynsGroupMember(String groupId) {
//        dismissCommonPostingDialog();
        if (!isFromInvite){
            CCPAppManager.startChattingAction(this, groupId,
                    mGroup.getName());
        }
        finish();

    }

    public class MyScrollListener extends OnRecyclerViewScrollListener {

        @Override
        public void onScrollUp() {

        }

        @Override
        public void onScrollDown() {

        }

        @Override
        public void onBottom() {
            toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
        }

        @Override
        public void onMoved(int distanceX, int distanceY) {

        }
    }
}
